package com.opengroupe.service.common.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.opengroupe.dao.AccessCodeDao;
import com.opengroupe.dao.CandidatDao;
import com.opengroupe.dao.CategorieDao;
import com.opengroupe.entities.AccessCode;
import com.opengroupe.entities.Candidat;
import com.opengroupe.entities.CandidatReponseQuestion;
import com.opengroupe.entities.Categorie;
import com.opengroupe.service.common.CommonService;
import com.opengroupe.util.HeavyResultatQuestionnaire;
import com.opengroupe.util.QrhUtil;

/**
 * Implements the {@link CommonService}
 * 
 * @author MMB11447
 * 
 */
public class CommonServiceImpl implements CommonService {

	@Autowired
	private AccessCodeDao accessCodeDao;
	
	@Autowired
	private CandidatDao candidatDao;
	
	@Autowired
	private CategorieDao categorieDao;

	@Override
	public AccessCode getGeneratedAccessCode() {
		AccessCode accessCode = accessCodeDao.lastGeneratedCode();
		if (accessCode != null) {
			if (isGeneratedToday(accessCode.getGenerationDate())) {
				return accessCode;
			}
		}
		
		String code = QrhUtil.generateAccessCode();
		accessCode = new AccessCode(code, new Date());
		
		try {
			accessCode = accessCodeDao.persist(accessCode);
		} catch (Exception ex) {
			// if ever the access code exists in the database, it'll be updated
			try {
				accessCode = accessCodeDao.merge(accessCode);
			} catch (Exception e) {
				return null;
			}
		}
		
		return accessCode;
	}

	@Override
	public boolean identification(String codeAcces) {
		AccessCode accessCode = accessCodeDao.findById(codeAcces);
		if (accessCode != null) {
			if (isGeneratedToday(accessCode.getGenerationDate())) {
				return true;
			}
		}
		return false;
	}

	@Transactional
	public HeavyResultatQuestionnaire consulterResultat(Candidat candidat) {
		if(candidat == null) {
			return null;
		}
		
		candidat = candidatDao.findByEmail(candidat.getEmailCandidat());
		
		List<CandidatReponseQuestion> crq = candidat.getCandidatreponsequestions();
		if(crq.size() == 0){
			return null;
		}
		return QrhUtil.corrigerQuestions(crq);
	}

	/**
	 * Checks if the given date is today (ignoring time).
	 * 
	 * @param generationDate
	 *            {@link Date} to be checked
	 * @return <code>true</code> if date is today. <code>false</code> otherwise.
	 */
	private boolean isGeneratedToday(Date generationDate) {
		Calendar cal1 = Calendar.getInstance();
		cal1.setTime(new Date());
		Calendar cal2 = Calendar.getInstance();
		cal2.setTime(generationDate);

		return QrhUtil.isSameDay(cal1, cal2);
	}
	
	@Override
	public List<Categorie> allCategorie() {
		return categorieDao.all();
	}
}
